package com.example.android.fragments

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.viewpager.widget.ViewPager
import com.daimajia.swipe.SwipeLayout
import com.example.android.R
import com.example.android.activities.MainActivity
import com.example.android.adapters.AnnounceRecyclerViewAdapter
import com.example.android.adapters.AnnounceViewPagerAdapter
import com.example.android.extensions.Alert
import com.example.android.extensions.Services
import com.example.android.models.Announce
import com.example.android.viewmodels.AnnounceViewModel
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.tabs.TabLayout
import com.mlsdev.animatedrv.AnimatedRecyclerView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


/**
 * @ClassName AnnounceFragment
 * @Author Ryan Kamanri
 * @Date 2022/6/1
 * @Description
 **/
class AnnounceFragment : Fragment() {
    // TODO: Rename and change types of parameters

    private val _Model : AnnounceViewModel by activityViewModels()

    private lateinit var _NewsView: View
    private lateinit var _AnnounceView: View
    private enum class CurrentView {
        NEWS_VIEW, ANNOUNCE_VIEW
    }
    // 当前所在页面
    private var _CurrentView = CurrentView.NEWS_VIEW

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _NewsView = inflater.inflate(R.layout.view_announce, container, false)
        _AnnounceView = inflater.inflate(R.layout.view_announce, container, false)
        return inflater.inflate(R.layout.fragment_announce, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 0. 准备好数据
        val newsList = _Model.NewsList
        val newsRecyclerView = _NewsView.findViewById<AnimatedRecyclerView>(R.id.announce_recycler_view)
        val newsAdapter = AnnounceRecyclerViewAdapter(requireContext(), newsList)

        val announceList = _Model.AnnounceList
        val announceRecyclerView = _AnnounceView.findViewById<AnimatedRecyclerView>(R.id.announce_recycler_view)
        val announceAdapter = AnnounceRecyclerViewAdapter(requireContext(), announceList)

        val viewPager = view.findViewById<ViewPager>(R.id.announce_view_pager)
        val tabLayout = view.findViewById<TabLayout>(R.id.announce_tab_layout)

        val views = arrayListOf(_NewsView, _AnnounceView)
        val titles = arrayListOf("新闻中心", "重要通知")
        viewPager.adapter = AnnounceViewPagerAdapter(views, titles)

        tabLayout.setupWithViewPager(viewPager)

        // 添加viewpager滑动页面事件
        viewPager.addOnPageChangeListener(object: ViewPager.OnPageChangeListener{
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {}

            override fun onPageSelected(position: Int) {
                when(position) {
                    0 -> _CurrentView = CurrentView.NEWS_VIEW
                    1 -> _CurrentView = CurrentView.ANNOUNCE_VIEW
                }
            }

            override fun onPageScrollStateChanged(state: Int) {}

        })


        // 1. 通过协程初始化(需要从主线程开始)
        lifecycleScope.launch(Dispatchers.Main) {
            if (newsList.isEmpty()) {
                kotlin.runCatching {
                    Services.AnnounceService.AppendAnnounce(announceList)
                    Services.AnnounceService.AppendNews(newsList)
                }.onFailure {

                    Alert("系统或网络错误, 请稍后重试 (${it.message})", Snackbar.LENGTH_INDEFINITE)
                    Log.e(toString(), "Failed To Execute GetAnnounceSuspend Caused By: ${it.message}")

                    it.printStackTrace()
                }
            }
            delay(1000)

            newsRecyclerView.adapter = newsAdapter
            newsRecyclerView.scheduleLayoutAnimation()
            newsRecyclerView.notifyDataSetChanged()

            announceRecyclerView.adapter = announceAdapter
            announceRecyclerView.notifyDataSetChanged()

        }

        // 2. 添加判断能否下拉事件
        (requireActivity() as MainActivity).SetCheckCanDoRefresh {

            if(_CurrentView == CurrentView.NEWS_VIEW &&
                newsRecyclerView != null &&
                newsRecyclerView.canScrollVertically(-1))
                    return@SetCheckCanDoRefresh false
            if(_CurrentView == CurrentView.ANNOUNCE_VIEW &&
                announceRecyclerView != null &&
                announceRecyclerView.canScrollVertically(-1))
                    return@SetCheckCanDoRefresh false
            return@SetCheckCanDoRefresh true
        }

        // 3. 添加下拉刷新事件
        (requireActivity() as MainActivity).SetOnRefreshSuspend {
            announceList.clear()
            newsList.clear()
            Services.AnnounceService.AppendAnnounce(announceList)
            Services.AnnounceService.AppendNews(newsList)
            Log.d(toString(), "News Count: ${newsList.size}")
            delay(1000)
            newsRecyclerView.notifyDataSetChanged()
            announceRecyclerView.notifyDataSetChanged()
        }



        // 4. 添加Item点击事件
        newsAdapter.SetOnItemClickListener { item, itemView ->
            TurnToItemFragment(item, itemView)
        }

        announceAdapter.SetOnItemClickListener { item, itemView ->
            TurnToItemFragment(item, itemView)
        }

    }

    private fun TurnToItemFragment(item: Announce, itemView: View) {
        // 判断是否向右拉开, 如拉开则不打开页面
        val swipe = itemView.findViewById<SwipeLayout>(R.id.announce_item_swipe)
        when(swipe.openStatus){
            SwipeLayout.Status.Close -> {}
            else -> return
        }

        val ItemFragment = AnnounceContentFragment(item)
        requireActivity().supportFragmentManager
            .beginTransaction()
            .setCustomAnimations(
                R.anim.fragment_item_select_in,
                R.anim.fragment_item_select_out,
                R.anim.fragment_item_back_in,
                R.anim.fragment_item_back_out)
            .replace(R.id.content_main_fragment, ItemFragment)
            .addToBackStack(null)
            .commit()
    }

}